package logic

import (
	"common/model"
	"context"
	"errors"
	"fmt"
	"log"
	product "product_server/proto"
	"strconv"
	"time"
)

// StartBargain 用户发起砍价
func (p *ProductServer) StartBargain(ctx context.Context, req *product.StartBargainRequest) (*product.StartBargainResponse, error) {
	// 幂等性校验：判断是否已存在未完成的砍价订单
	existOrder, err := model.ExistOrder(req.UserId, req.ProductId, []int64{0, 3})
	if err == nil {
		// 查询砍价扩展表
		existBargain, err2 := model.ExistBargain(existOrder.Id, req.ActivityId)
		fmt.Println(existBargain)
		if err2 == nil {
			return &product.StartBargainResponse{
				OrderId:      existOrder.Id,
				CurrentPrice: existBargain.CurrentPrice,
				CurrentCuts:  existBargain.CurrentCuts,
				Status:       existBargain.Status,
				Message:      "已存在未完成的砍价订单，直接返回",
			}, nil
		}
	}
	fmt.Println(existOrder)
	// 1. 校验砍价活动是否存在且有效
	bargainActivity, err := model.GteBargainActivity(req.ActivityId, req.ProductId)
	if err != nil {
		return nil, errors.New("砍价活动不存在")
	}
	if time.Now().Before(bargainActivity.StartTime) || time.Now().After(bargainActivity.EndTime) {
		return nil, errors.New("砍价活动未开始或已结束")
	}
	if bargainActivity.Stock <= 0 {
		return nil, errors.New("砍价库存不足")
	}
	// 生成砍价订单号
	orderNo := "BG" + time.Now().Format("20060102150405") + strconv.FormatInt(req.UserId, 10)
	log.Printf("创建砍价订单号: %s", orderNo)
	// 2. 创建主订单
	order := &model.OrderMaster{
		OrderNo:       orderNo,
		UserId:        req.UserId,
		ProductId:     req.ProductId,
		OrderType:     3, // 3=砍价订单
		OriginalPrice: float64(bargainActivity.OriginalPrice),
		ActualPrice:   float64(bargainActivity.OriginalPrice), // 初始为原价
		Quantity:      1,
		Status:        3, // 3=待支付
		CreatedAt:     time.Now(),
		UpdatedAt:     time.Now(),
	}
	order, err = model.OrderCrete(order)
	if err != nil {
		return nil, errors.New("主订单创建失败")
	}

	// 3. 创建砍价订单扩展表
	orderBargain := &model.OrderBargain{
		OrderId:      order.Id,
		ActivityId:   req.ActivityId,
		CurrentPrice: bargainActivity.OriginalPrice,
		CurrentCuts:  1,
		Status:       0, // 0=砍价中
		ExpireTime:   bargainActivity.EndTime,
		CreatedAt:    time.Now(),
		UpdatedAt:    time.Now(),
	}
	err = model.OrderBargainCreate(orderBargain)
	if err != nil {
		return nil, errors.New("砍价订单扩展创建失败")
	}

	// 4. 写入首条砍价记录（发起者）
	bargainRecord := &model.BargainRecord{
		OrderId:    order.Id,
		ActivityId: req.ActivityId,
		ProductId:  req.ProductId,
		UserId:     req.UserId,
		UserType:   0, // 0=发起者
		CutAmount:  0, // 首次发起不砍价
		CreatedAt:  time.Now(),
	}
	err = model.BargainRecordCreate(bargainRecord)
	if err != nil {
		return nil, errors.New("砍价记录创建失败")
	}

	// 5. 扣减库存
	err = model.DeductBargainProductStock(req.ActivityId)
	if err != nil {
		return nil, errors.New("砍价库存扣减失败")
	}

	// 6. 返回响应
	resp := &product.StartBargainResponse{
		OrderId:      order.Id,
		CurrentPrice: orderBargain.CurrentPrice,
		CurrentCuts:  orderBargain.CurrentCuts,
		Status:       orderBargain.Status,
		Message:      "砍价发起成功",
	}
	return resp, nil
}
